package org.timeismoney.payment.web.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.timeismoney.payment.exception.BizException;
import org.timeismoney.payment.model.ItemPaymentDetail;
import org.timeismoney.payment.model.PaymentRecord;
import org.timeismoney.payment.model.SchoolYear;
import org.timeismoney.payment.model.Student;
import org.timeismoney.payment.service.PaymentRecordService;
import org.timeismoney.payment.web.WebUtils;

import store.pay.ConfigObjectHelper;
import store.pay.icbc.IcbcB2cConfigObject;
import store.pay.icbc.IcbcB2cPayObject;
import store.util.PayConfig;

public class PayRecordAction extends BaseAction {
	private static Logger		log	= Logger.getLogger(PayRecordAction.class);
	private PaymentRecordService service;

	public void setService(PaymentRecordService service) {
		this.service = service;
	}

	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			String[] itemPaymentNos = request.getParameterValues("itemPaymentNo[]");
			String[] schoolYearNos = request.getParameterValues("schoolYearNo[]");
			String[] stuNos = request.getParameterValues("stuNo[]");
			String[] payments = request.getParameterValues("payment[]");
			if (ArrayUtils.isEmpty(itemPaymentNos)
					|| ArrayUtils.isEmpty(schoolYearNos)
					|| ArrayUtils.isEmpty(stuNos) || ArrayUtils.isEmpty(payments)
					|| !ArrayUtils.isSameLength(itemPaymentNos, payments)) {
				throw new BizException("参数传递有误");
			}
			String recordNo = WebUtils.getTimeString()+(new Random()).nextInt(1000);
			List<PaymentRecord> records = new ArrayList<PaymentRecord>();
			PaymentRecord finRecord = null;
			BigDecimal total = new BigDecimal(0);
			Date date = new Date();
			for (int i = 0; i < itemPaymentNos.length; i++) {
				String itemPaymentNo = itemPaymentNos[i];
				ItemPaymentDetail itemPaymentDetail = new ItemPaymentDetail();
				itemPaymentDetail.setItemPaymentNo(Integer.valueOf(itemPaymentNo));
				SchoolYear year = new SchoolYear();
				year.setSchoolYearNo(Integer.valueOf(schoolYearNos[i]));
				PaymentRecord paymentRecord = new PaymentRecord(itemPaymentDetail, year, recordNo, BigDecimal.valueOf(Double.valueOf(payments[i])), false);
				Student stu = new Student();
				stu.setStuNo(stuNos[i]);
				paymentRecord.setStudent(stu);
				paymentRecord.setCreateDate(date);
				if("-1".equals(itemPaymentNo)){
					finRecord = paymentRecord;
				}else
					records.add(paymentRecord);
				total = total.add(paymentRecord.getPayment());
			}
			service.createOrder(records,finRecord);
			renderJson(response, "{\"recordNo\":\""+recordNo+"\", \"total\":\""+total.doubleValue()+"\"}");
		} catch (Exception e) {
			log.error(e.getMessage());
			renderJson(response, WebUtils.generateErrorJSON("生成转账单失败 "+e.getMessage()));
		}
		return null;
	}

	public ActionForward finish(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		try {
			String paymentRecordNo = request.getParameter("paymentRecordNo");
			String money = request.getParameter("money");
			if(StringUtils.isEmpty(paymentRecordNo)||StringUtils.isEmpty(money)){
				throw new BizException("参数传递有误");
			}
			String amount="0";
			float cost = 0;
			try {
				cost = Float.valueOf(money).floatValue();
				amount=String.valueOf((int)(cost*100));
			} catch (Exception e) {
				throw new BizException("参数传递有误");
			}
			/***************************************************************************/
			String path = request.getScheme() + "://" + request.getServerName() + request.getContextPath();

			System.out.println(path);
			String goodsID="001";
			String goodsName="xuezafei";
			String goodsNum="1";

			IcbcB2cPayObject icbcB2c = new IcbcB2cPayObject();
			IcbcB2cConfigObject ico = (IcbcB2cConfigObject) ConfigObjectHelper.getConfig(IcbcB2cConfigObject.class);

			icbcB2c.setOrderid(paymentRecordNo);
			icbcB2c.setAmount(amount);

			icbcB2c.setGoodsID(goodsID);
			icbcB2c.setGoodsName(goodsName);
			icbcB2c.setGoodsNum(goodsNum);

			icbcB2c.setMerAcct(ico.getMerAcct());
			icbcB2c.setMerID(ico.getMerID());
			icbcB2c.setMerURL(path + "/pay/notify/icbc/b2c/server");
			icbcB2c.setNotifyType("HS");
			icbcB2c.setVerifyJoinFlag("0");
			icbcB2c.setResultType("0");
			icbcB2c.setGoodsType("0");

			icbcB2c.setMerReference(PayConfig.MERREFERENCE);
			icbcB2c.setMerCustomIp(request.getRemoteAddr());

			icbcB2c.setMerCustomID("00000000112");
			icbcB2c.setMerCustomPhone("13599648573");
			icbcB2c.setMerOrderRemark("xuezafei");

			System.out.println(icbcB2c.getMerURL());
			icbcB2c.setTranData(icbcB2c.tranData());
			icbcB2c.setMerSignMsg(icbcB2c.sign());
			
			System.out.println(icbcB2c.tranDataXml());
			System.out.println(icbcB2c.tranData());
			System.out.println(icbcB2c.sign());

			store.pay.ValidationMsg vm = icbcB2c.validation();
			request.setAttribute(store.pay.AutoPayServlet.ATTR_NAME_PAY_OBJECT, icbcB2c);
			request.setAttribute(store.pay.AutoPayServlet.ATTR_NAME_FROM_ACTION, PayConfig.BANKURL);
			request.getRequestDispatcher("/AutoPayServlet").forward(request, response);
			//service.finish(paymentRecordNo,cost);
		} catch (Exception e) {
			log.error(e.getMessage());
			renderJson(response, WebUtils.generateErrorJSON("转账出错："+" "+e.getMessage()));
		}
		return null;
	}

}
